package com.syni.mdd.yhd.common.all.service;

import com.syni.mdd.sjb.common.component.utils.common.utils.ResultMapHelper;
import com.syni.mdd.sjb.common.component.utils.feign.dto.mddDspApi.CreateNewsDto;
import com.syni.mdd.yhd.common.all.constants.Constants;
import com.syni.mdd.yhd.common.all.constants.ResultCode;
import com.syni.mdd.yhd.common.all.constants.ResultMsg;
import com.syni.mdd.yhd.common.all.dao.jpa.BmsDxNewsDao;
import com.syni.mdd.yhd.common.all.entity.*;
import com.syni.mdd.yhd.common.all.entity.bo.common.MddDxshAppNewAdapterBo;
import com.syni.mdd.yhd.common.all.entity.user.BmsUser;
import com.syni.mdd.yhd.common.all.service.impl.BaseService;
import com.syni.mdd.yhd.common.all.utils.SpecificationUtils;
import com.syni.mdd.yhd.common.all.utils.StringUtils;
import com.syni.mdd.yhd.common.all.utils.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @className BmsUserOperationLogService
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class BmsDxNewsService extends BaseService<BmsDxNews, Integer> {
    //用户系统消息
    public final static int PARENTTYPT_SYS = 0;
    //用户互动消息
    public final static int PARENTTYPT_INT = 1;
    //互动消息_点赞
    public final static int PARENTTYPT_INT_LIKE = 1;
    //互动消息_评论
    public final static int PARENTTYPT_INT_COMMENT = 2;
    //互动消息_回复
    public final static int PARENTTYPT_INT_ANSWER = 3;
    //互动消息_发布视频
    public final static int PARENTTYPT_INT_RELEASE_VIDEO = 4;
    //消费消息
    public final static int PARENTTYPT_CON = 2;
    //商家促销消息
    public final static int PARENTTYPT_PRO = 3;
    //用户收促销消息
    public final static int PARENTTYPT_PRO_ORDINARY = 1;


    @Value("${app.interactNews.num}")
    private Integer appInteractNewsNum;
    @Autowired
    BmsDxNewsDao bmsDxNewsDao;

    @Autowired
    BmsVideoService bmsVideoService;

    @Autowired
    BmsUserVideoLikeService bmsUserVideoLikeService;

    @Autowired
    BmsBusinessGroupMessageService bmsBusinessGroupMessageService;

    @Autowired
    BmsBusinessService bmsBusinessService;

    @Autowired
    BmsUserBusinessService bmsUserBusinessService;

    @Autowired
    BmsDxClientRoleService bmsDxClientRoleService;

    @Autowired
    BmsDxUserPermissionService bmsDxUserPermissionService;


    @Override
    public BmsDxNewsDao getBaseDao() {
        return bmsDxNewsDao;
    }

    public Map<String, Object> findUserClientNews(Integer userId,Integer newType,Integer pageNum,Integer pageSize) {
        List<BmsDxNews> bmsDxNewsList = new LinkedList<>();
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "updateTime");
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("bmsUserId",userId);
        conditionMap.put("parentType",newType);
        conditionMap.put("originRole",Constants.GENERAL_USER_ROLE_ID);
        bmsDxNewsList.addAll(bmsDxNewsDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent());
        if(newType == PARENTTYPT_SYS) {
            //处理
        }else if(newType == PARENTTYPT_INT){
            //处理用户的点赞集
            handBmsDxNewsListLikeQue(bmsDxNewsList);
        }else if(newType == PARENTTYPT_CON){

        }else if(newType == PARENTTYPT_PRO){
            //处理促销消息
            handBmsDxNewsListPro(userId,bmsDxNewsList);
        }
        return ResultMapHelper.success(bmsDxNewsList, ResultMsg.HAND_SUCCESS);
    }

    /**
     * @Description: 查询该消息有多少未读消息
     * @Author: cfx
     * @Date: 2019/4/8
     */
    public void handBmsDxNewsListPro(Integer userId,List<BmsDxNews> bmsDxNewsList) {
        if(bmsDxNewsList != null && bmsDxNewsList.size() > 0){
            Set<Integer> businessIds = new HashSet<>();
            for(BmsDxNews bmsDxNews : bmsDxNewsList){
                businessIds.add(bmsDxNews.getBmsBusinessId());
            }
            if(businessIds.size() > 0){
                Map<Integer,Integer> recordBusinessNum = new HashMap<>();
                Map<Integer,BmsBusiness> bmsBusinessMap = bmsBusinessService.findBusinessByIds(businessIds);
                List<Map<String,Object>> newBusinessMessageNum = bmsBusinessGroupMessageService.getBaseDao().
                        selfFindUserBusinessMessage(userId,businessIds,Integer.parseInt(Constants.COMMON_FLAG_FALSE));
                if (newBusinessMessageNum != null && newBusinessMessageNum.size() > 0){
                    for(Map<String,Object> messageNum : newBusinessMessageNum){
                        recordBusinessNum.put(Integer.parseInt(messageNum.get("businessId").toString()),
                                Integer.parseInt(messageNum.get("num").toString()));

                    }
                }
                for(BmsDxNews bmsDxNews : bmsDxNewsList){
                    if(recordBusinessNum.containsKey(bmsDxNews.getBmsBusinessId())){
                        bmsDxNews.setIsNoRead(recordBusinessNum.get(bmsDxNews.getBmsBusinessId()));
                    }
                    if(bmsBusinessMap.containsKey(bmsDxNews.getBmsBusinessId())){
                        bmsDxNews.setBusinessImg(bmsBusinessMap.get(bmsDxNews.getBmsBusinessId()).getLogoUrl());
                    }
                }
            }
        }
    }

    /**
     * @Description: 处理点赞集合获取不够问题
     * @Author: cfx
     * @Date: 2019/4/8
     */
    public void handBmsDxNewsListLikeQue(List<BmsDxNews> bmsDxNewsList) {
        Set videoIds = new HashSet();
        for(BmsDxNews bmsDxNews : bmsDxNewsList){
            if (bmsDxNews.getParentType() == BmsDxNewsService.PARENTTYPT_INT &&
                    bmsDxNews.getChildType() == BmsDxNewsService.PARENTTYPT_INT_LIKE) {
                videoIds.add(bmsDxNews.getBmsVideoId());
            }
        }
        Map<Integer,List<Map<String,Object>>> resultMap = new HashMap<>();
        Map<Integer,Integer> videoLikeNumMap = new ConcurrentHashMap<>();
        if(videoIds.size() > 0){
            int startIndex = 1;
            List<Map<String,Object>> bmsUserVideoLikeList = bmsUserVideoLikeService.getBaseDao().selfFindByVideoIds(videoIds);
            if(bmsUserVideoLikeList != null && bmsUserVideoLikeList.size() > 0){
                for(Map<String,Object> bmsUserVideoLike : bmsUserVideoLikeList){
                    Integer videoId = Integer.parseInt(bmsUserVideoLike.get("bms_video_id").toString());
                    if(videoLikeNumMap.containsKey(videoId)){
                        videoLikeNumMap.put(videoId,videoLikeNumMap.get(videoId) + 1);
                        if(videoLikeNumMap.get(videoId) > appInteractNewsNum){
                            continue;
                        }
                    }else {
                        videoLikeNumMap.put(videoId,startIndex);
                    }
                    List<Map<String,Object>> list = new LinkedList<>();
                    Map<String,Object> userMap = new HashMap<>();
                    if(resultMap.containsKey(videoId)) {
                        list = resultMap.get(videoId);
                    }else {
                        resultMap.put(videoId,list);
                    }
                    Integer userId = Integer.parseInt(bmsUserVideoLike.get("bms_user_id").toString());
                    userMap.put("userid",userId);
                    userMap.put("loginName","");
                    BmsUser bmsUser = TokenManager.getUser(userId);
                    if(bmsUser != null){
                        String loginName = bmsUser.getLoginName();
                        userMap.put("loginName",loginName != null ?
                                 loginName : bmsUser.getSystemUser().getLoginName() == null ?
                                "" : bmsUser.getSystemUser().getLoginName());
                    }
                    list.add(userMap);

                }
            }
        }
        for(BmsDxNews bmsDxNews : bmsDxNewsList){
            if (bmsDxNews.getParentType() == BmsDxNewsService.PARENTTYPT_INT &&
                    bmsDxNews.getChildType() == BmsDxNewsService.PARENTTYPT_INT_LIKE) {
                if(resultMap.containsKey(bmsDxNews.getBmsVideoId())){
                    List<Map<String,Object>> userList = resultMap.get(bmsDxNews.getBmsVideoId());
                    bmsDxNews.setUserList(userList);
                }
                if(videoLikeNumMap.containsKey(bmsDxNews.getBmsVideoId())){
                    bmsDxNews.setUserLikeNum(videoLikeNumMap.get(bmsDxNews.getBmsVideoId()));
                }
            }
        }
    }

    public Map<String,Object> findBusinessClientNews(Integer userId,Integer businessId,
                                                     Integer newType,Integer pageNum,Integer pageSize){
        Map<String,Object> conditionMap = new HashMap<>();
        conditionMap.put("bmsBusinessId",businessId);
        conditionMap.put("parentType",newType);
        //检验是否是商家或者店员
        if(bmsUserBusinessService.checkBusinessIsAssistan(userId,businessId)){
            conditionMap.put("originRole",Constants.ASSISTANT_ROLE_ID);
        }else {
            Map<String,Object> checkMap = bmsUserBusinessService.checkBusinessIsHaving(userId,businessId);
            if(!ResultCode.CODE_NORMAL.equals(checkMap.get("status").toString())){
                return checkMap;
            }
            conditionMap.put("originRole",Constants.BUSINESS_ROLE_ID);
        }
        Pageable pageable = PageRequest.of(pageNum - 1, pageSize, Sort.Direction.DESC, "newTime");
        List<BmsDxNews> bmsDxNewsList = bmsDxNewsDao.findAll(new SpecificationUtils(conditionMap),pageable).getContent();
        if(newType == PARENTTYPT_SYS) {
            //处理
        }else if(newType == PARENTTYPT_INT){
            //处理用户的点赞集
            handBmsDxNewsListLikeQue(bmsDxNewsList);
        }
        return ResultMapHelper.success(bmsDxNewsList,"查找成功");
    }

    public Map<String,Object> createFxNews(CreateNewsDto createNewsDto){
        BmsDxNews bmsDxNews = new BmsDxNews();
        bmsDxNews.setBmsUserId(createNewsDto.getUserId());
        bmsDxNews.setParentType(0);
        bmsDxNews.setChildType(17);
        bmsDxNews.setContent(createNewsDto.getContent());
        bmsDxNews.setNewTime(new Date());
        bmsDxNews.setUpdateTime(new Date());
        bmsDxNews.setOriginRole(1);
        bmsDxNewsDao.save(bmsDxNews);
        return ResultMapHelper.success(bmsDxNews.getId());
    }

    public  List<BmsDxNews> trunResult(Page<BmsDxNews> bmsDxNews) {
        List<BmsDxNews> bmsDxNewsList = new ArrayList<>();
        if(bmsDxNews.getContent() != null){
            for(BmsDxNews bmsDxNews1 : bmsDxNews.getContent()){
                bmsDxNewsList.add(bmsDxNews1);
            }
        }
        return bmsDxNewsList;
    }

    public Map<String, Object> findTopOnceType(Integer userId) {
        List<BmsDxNews> bmsDxNewsList = bmsDxNewsDao.findUserClientOnceTypeTop(userId);
        handBmsDxNewsListLikeQue(bmsDxNewsList);
        return ResultMapHelper.success(bmsDxNewsList,"查找成功");
    }

    public Map<String, Object> findBusinessTopNew(Integer userId,Integer businessId) {
        List<BmsDxNews> bmsDxNewsList = new ArrayList<>();
        //查询在商户端的角色
        Set<Integer> roleIds = new HashSet<>();
        roleIds.add(Constants.BUSINESS_ROLE_ID);
        roleIds.add(Constants.ASSISTANT_ROLE_ID);
        List<BmsDxClientRole> bmsDxClientRoles = bmsDxClientRoleService.getUserClienRole(userId,roleIds);
        if(!(bmsDxClientRoles != null && bmsDxClientRoles.size() > 0)){
            return ResultMapHelper.failure(ResultMsg.ADMIN_ERROR);
        }
        BmsDxClientRole bmsDxClientRole = bmsDxClientRoles.get(0);
        bmsDxNewsList = bmsDxNewsDao.findBusinessTopNews(bmsDxClientRoles.get(0).getRoleId(),businessId);
        if(bmsDxClientRole.getRoleId() == Constants.ASSISTANT_ROLE_ID){
            if(!bmsDxUserPermissionService.checkUserPermission(userId,Constants.ASSISTANT_ROLE_ID,Constants.VIDEO_MAN)){
                handNoShowHuDongNews(bmsDxNewsList);
            }
        }
        handBmsDxNewsListLikeQue(bmsDxNewsList);
        return ResultMapHelper.success(bmsDxNewsList,"查找成功");
    }

    public void handNoShowHuDongNews(List<BmsDxNews> bmsDxNewsList){
        if(bmsDxNewsList != null && bmsDxNewsList.size() > 0){
            Iterator<BmsDxNews> iterator = bmsDxNewsList.iterator();
            while (iterator.hasNext()){
                BmsDxNews bmsDxNews = iterator.next();
                if(bmsDxNews.getParentType() == Constants.PARENTTYPT_INT){
                    iterator.remove();
                }
            }
        }
    }

    public String getBmsNewsTitle(Integer userId){
        String loginName = "";
        BmsUser bmsUser = TokenManager.getUser(userId);
        if(bmsUser != null){
            loginName = bmsUser.getLoginName();
            if(StringUtils.isBlank(loginName)){
                SystemUser systemUser = bmsUser.getSystemUser();
                if(systemUser != null){
                    loginName = systemUser.getCustomName();
                }
            }
        }
        return loginName;
    }

    public void saveNews(BmsDxNews bmsDxNews,BmsVideo bmsVideo){
        Date nowTime = new Date();
        bmsDxNews.setNewTime(nowTime);
        bmsDxNews.setUpdateTime(nowTime);
        bmsDxNews.setVideoImg(bmsVideo.getCloudFileSnapshot10Url());
        bmsDxNews.setVideoName(bmsVideo.getVendorName());
        bmsDxNewsDao.save(bmsDxNews);
    }

    public static MddDxshAppNewAdapterBo mddDxshAppNewAdapter(BmsDxNews bmsDxNews){
        if(MddDxshAppNewAdapterBo.getMddDxshAppNewAdapterBoHashMap().containsKey(bmsDxNews.getParentType() + "_" + bmsDxNews.getChildType())){
            return MddDxshAppNewAdapterBo.getMddDxshAppNewAdapterBoHashMap().get(bmsDxNews.getParentType() + "_" + bmsDxNews.getChildType());
        }
        return null;
    }
}
